package com.kumz.SpringMVC.controller;

import com.kumz.SpringMVC.pojo.User;
import com.kumz.SpringMVC.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

/**
 * Author: Yunz
 * E-mail: 1603754314@qq.com
 * Date: 2022/12/12
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    //查询所有的用户
    @RequestMapping("/allUser")
    public String allUser(Model model){
        List<User> users = userService.selectAllUser();
        model.addAttribute("list",users);
        return "/admin/html/admin-list";
    }
    //点击【添加】时，跳转到添加页面
    @RequestMapping("/toAddUser")
    public String toAddUser(){
        return "addUser";
    }
    //添加用户
    @RequestMapping("/addUser")
    public String addUser(User user){
        userService.addUser(user);
        return "redirect:/admin/html/admin-list";
    }
    //点击【修改】时，跳转到修改页面
    @RequestMapping("/toUpdateUser")
    public String toUpdateUser(Model model,int id){
        User user = userService.selectUserById(id);
        model.addAttribute("user",user);
        return "updateUser";
    }
    //修改用户
    @RequestMapping("/updateUser")
    public String updateUser(User user){
        userService.updateUser(user);
        return "redirect:/admin/html/admin-list";
    }
    //删除
    @RequestMapping("/deleteUser/{id}")
    public String deleteUser(@PathVariable("id") int id){
        userService.deleteUserByName(id);
        return "redirect:/admin/html/admin-list";
    }

    //根据姓名查询用户
    @RequestMapping("/selectUserByName")
    public String selectUserByName(String username,Model model){

        User user = userService.selectUserByName(username);
        List<User> list=new ArrayList<User>();
        list.add(user);
        if(user==null){
            list = userService.selectAllUser();
            model.addAttribute("error","未查到");
        }
        model.addAttribute("list",list);
        return "/admin/html/admin-list";
    }
}
